<template>
    <div>
        <div class="flex-table-wrapper"><div :id.once="id" :class.once="classex"></div></div>
        <div class="flex-table-pager">
            <div class="pull-right pr15 pt5">
                <span class="pr10">共{{total}}条记录</span>
                <span class="pr10">
                    每页条数
                    <span class="dropup">
                        <button class="btn btn-default btn-xs" type="button" data-toggle="dropdown">
                            {{pageSize}}
                            <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu" role="menu">
                            <li v-for="item in [500,200,100,50,20,10]">
                                <a role="menuitem" @click="changePageSize(item)">{{item}}</a>
                            </li>
                        </ul>
                    </span>
                </span>
                <a class="pr10 cp" @click="goPrev"><i class="fa fa-angle-left"></i></a>
                {{currentPage}}/{{totalPages}}
                <a class="pl10 cp" @click="goNext"><i class="fa fa-angle-right"></i></a>
            </div>
        </div>
    </div>
</template>
<script>

    import agGrid from "ag-grid";

    /**
     * 分页数据
     * @param params
     * @returns {{page: number, size: number}}
     * @constructor
     */
    window.DS_Params = function(params) {
        const size = params.endRow - params.startRow;
        let ret = {
            page: parseInt(params.startRow / size) + 1,
            size
        };

        if (params.sortModel.length) {
            ret.orderby = params.sortModel[0].colId + ' ' + params.sortModel[0].sort;
        }

        return ret;
    };

    export default {
        data() {
            return {
                'api': null,
                'columnApi': null,
                'grid': null,
                'gridEl': null,
                'selAllEL': null,
                'gridOpts': null,
                'ver': 1,
                'overlayLoadingText': '数据加载中...',
                'overlayNoRowsText': '暂无数据'
            };
        },
        props: {
            id: {
                required: true,
                type: String
            },
            'uclass': String,
            'height': String,
            dataSource: Object
        },
        mounted() {
            let flexTable = this;

            this.$on('ds.changed', () => {
                this.pager.rowCount = this.ds.rowCount;
                this.pager.calculateTotalPages();

                this.ver ++;
            });


            let columns = this.ds.columns;
            let actions = this.ds.actions;

            columns.forEach(function(e) {
                if (e.width || e.minWidth || e.maxWidth) {
                    e.suppressSizeToFit = true;
                }
            });

            columns.unshift({
                headerName: "",
                field: "_id",
                pinned: 'left',
                suppressResize: true,
                suppressMovable: true,
                suppressSizeToFit: true,
                suppressSorting: true,
                suppressToolPanel: true,
                width: 40,
                cellStyle: function(params) {
                    return {textAlign: 'center'};
                },
                headerCheckboxSelection: true,
                headerCheckboxSelectionFilteredOnly: true,
                checkboxSelection: true

            });

            if (actions.length) {
                _.each(actions, function(item) {
                    if (item.url) {
                        item.url = _.template(item.url);
                    }
                });

                function makeItemActionHandler(act, row) {
                    return function() {
                        flexTable.$emit('row-action', act, row);
                    };
                }

                columns.unshift({
                    headerName: "操作",
                    field: "__actions",
                    pinned: 'right',
                    suppressSizeToFit: true,
                    width: 80,
                    cellRenderer: (row) => {
                        const item = row.data;
                        if (item.__actionsDiv) {
                            return item.__actionsDiv;
                        }

                        item.__actionsDiv = $('<div></div>').get(0);

                        for (let i = 0; i < actions.length; i ++) {
                            const btn= $(`<a class="btn btn-info btn-xs mr5" href="${!actions[i].url ? 'javascript:;' : actions[i].url(item)}" title="${actions[i].label}"><i class="fa ${actions[i].icon}"></i></a>`);

                            if (!item.__actions) {
                                item.__actions = {};
                            }

                            if (!actions[i].url) {
                                item.__actions[actions[i].name] = makeItemActionHandler(actions[i], row);
                            	btn.click(item.__actions[actions[i].name]);
							}

                            btn.appendTo(item.__actionsDiv);
                        }
                        return item.__actionsDiv;
                    }

                });
            }

            let gridOptions = this.gridOpts = {
                defaultColDef: {
                    suppressSorting: true,
                    suppressMenu: true
                },
                columnDefs: columns,
                headerHeight: 40,
                rowHeight: 40,
                suppressContextMenu: true,
                suppressCellSelection: true,
                enableServerSideSorting: true,
                suppressMenuFilterPanel: true,
                suppressMenuMainPanel: true,
                suppressMultiSort: true,
                unSortIcon: true,
                enableColResize: true,
                paginationPageSize: 10,
                rowModelType: 'pagination',
                rowSelection: 'multiple',
                suppressRowClickSelection: true,
                overlayLoadingTemplate: `<span class="ag-overlay-loading-center">${this.ds && this.ds.loadingText || this.overlayLoadingText}</span>`,
                overlayNoRowsTemplate: `<span class="ag-overlay-no-rows-center">${this.overlayNoRowsText}</span>`,
                onGridReady: (event) => {
                    this.api = event.api;
                    this.columnApi = event.columnApi;

                    this.ds.grid(this);
                    this.api.setDatasource(this.ds);
                    resizeHandler();
                    resizing = setTimeout(resizeHandler, 500);
                }
            };


            let eGridDiv = document.querySelector(`#${this.id}`);
            let resizing = 0;
            const resizeHandler = function() {
                flexTable.api.sizeColumnsToFit();
            };

            $(eGridDiv).height(this.height);
            $(window).resize(function () {
                clearTimeout(resizing);
                resizing = setTimeout(resizeHandler, 60);
            });

            this.gridEl = eGridDiv;
            this.grid = new agGrid.Grid(eGridDiv, gridOptions);

        },
        computed: {
            classex() {
                return 'ag-bootstrap flex-table ' + (this.uclass || '');
            },
            ds() {
                return this.dataSource;
            },
            pager() {
                if (!this.grid) {
                    return null;
                }

                return this.grid.context.getBean('serverPaginationService');
            },
            total() {
                if (!this.pager) {
                    return 0;
                }

                return this.pager.rowCount + this.ver * 0;
            },
            pageSize() {
                if (!this.pager) {
                    return 0;
                }

                return this.pager.pageSize + this.ver * 0;

            },
            currentPage() {
                if (!this.pager) {
                    return 0;
                }

                return this.pager.currentPage + 1 + this.ver * 0;
            },
            totalPages() {
                if (!this.pager) {
                    return 0;
                }

                return this.pager.totalPages + this.ver * 0;
            }
        },
        methods: {
            /**
             * 上一页
             */
            goPrev() {
                if (this.currentPage - 1 > 0) {
                    this.pager.goToPreviousPage();
                    this.ver ++;
                }
            },
            /**
             * 下一页
             */
            goNext() {
                if (this.currentPage + 1 <= this.totalPages) {
                    this.pager.goToNextPage();
                    this.ver ++;
                }
            },
            /**
             * 改变每页显示条数
             * @param size
             */
            changePageSize(size) {
                this.gridOpts.paginationPageSize = size;
                this.pager.pageSize = size;
                this.pager.calculateTotalPages();

                if (this.pager.currentPage > this.pager.totalPages) {
                    this.pager.currentPage = this.pager.totalPages - 1;
                }

                this.ver ++;

                this.pager.loadPage();
            },
            changeOverlayLoadingText(text) {
                if (text) {
                    this.overlayLoadingText = text;
                }

                this.gridOpts.overlayLoadingTemplate = `<span class="ag-overlay-loading-center">${this.overlayLoadingText}</span>`;
                $('.ag-overlay-loading-center', this.$el).text(this.overlayLoadingText);
            },
            changeOverlayNoRowsText(text) {
                if (text) {
                    this.overlayNoRowsText = text;
                }

                this.gridOpts.overlayNoRowsTemplate = `<span class="ag-overlay-no-rows-center">${this.overlayNoRowsText}</span>`;
                $('.ag-overlay-no-rows-center', this.$el).text(this.overlayNoRowsText);

            }
        }
    }
</script>

